class MySingleLinkedList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;//代表链表的头结点

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void display(ListNode newHead) {
        ListNode cur = newHead;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void addFirst(int val) {
        ListNode node = new ListNode(val);
        node.next = head;
        head = node;
    }
    public boolean chkPalindrome() {
        // write code here
        if (head == null) {
            return true;
        }
        //1. 找到链表的中间结点
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //2. 翻转中间结点 后面的链表
        ListNode cur = slow.next;
        while (cur != null) {
            ListNode curN = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curN;
        }
        //3. slow从后往前走 head从前往后 直到它俩相遇
        while (head != slow) {
            if (head.val != slow.val) {
                return false;
            }
            if (head.next == slow) {
                return true;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;
    }
}
public class Demo2_7 {
    //链表的回文结构
    //对于一个链表，请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法，判断其是否为回文结构。
    //给定一个链表的头指针head，请返回一个bool值，代表其是否为回文结构。保证链表长度小于等于900。
    public static void main(String[] args) {
        MySingleLinkedList msl = new MySingleLinkedList();
        msl.addFirst(1);
        msl.addFirst(2);
        msl.addFirst(3);
        msl.addFirst(2);
        msl.addFirst(1);
        msl.display();
        System.out.println("=======");
        Boolean ret=msl.chkPalindrome();
        System.out.println(ret);
    }
}
